//
//  MercPermanceListVC.swift
//  kxf
//
//  Created by Mac on 2024/3/24.
//

import Foundation
import MJRefresh
import MCToast

class MercPermanceListVC: WHBaseViewVC {
    
    var pageNum = 1
    var pageSize = 5
    var phone = ""
    var startTime = Date().getLast30Days()
    var endTime = Date().todayDate
    
    var dataSourceArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        dataSourceArray.addObjects(from: ["","","","","",""])
        initUI()
        sendDataListRequest()
    }
    
    lazy var topVm : PerformanceFilterVM = {
        let vm = PerformanceFilterVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight(), width:0, height: 0))
        vm.dataTitleVm.titleVm.titleLabel.text = "时间"
        vm.timeFilterAlertVm.controller = self
        vm.controller = self
        vm.timeFilterAlertVm.queryBlock = {(startTime,endTime)in
            self.topVm.dataTitleVm.contentLabel.text = "\(startTime)  -  \(endTime)"
            self.startTime = startTime
            self.endTime = endTime
            self.sendDataListRequest()
        }
        
        vm.queryBlock = {(startTime,endTime)in
            self.topVm.dataTitleVm.contentLabel.text = "\(startTime)  -  \(endTime)"
            self.startTime = startTime
            self.endTime = endTime
            self.sendDataListRequest()
        }
        return vm
    }()
    lazy var searchVm : SearchVM = {
        let vm = SearchVM.init(frame: CGRect.init(x: 0, y: self.topVm.frame.maxY, width: 0, height: 0))
        vm.backgroundColor = WHColor_16(colorStr: "efefef")
        vm.searchBlock = {()in
            self.phone = self.searchVm.textField.text ?? ""
            self.pageNum = 1
            self.sendDataListRequest()
        }
        return vm
    }()
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: self.searchVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.searchVm.frame.maxY+kFitWidth(10))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .COLOR_LIGHT_GREY
        vi.showsVerticalScrollIndicator = false
        
        vi.register(PerformanceMercTableViewCell.classForCoder(), forCellReuseIdentifier: "PerformanceMercTableViewCell")
        
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        vi.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.pageNum = 1
            self.sendDataListRequest()
        })

        vi.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.pageNum += 1
            self.sendDataListRequest()
        })
        
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
}

extension MercPermanceListVC{
    func initUI(){
        initNavi(titleStr: "我的商户业绩")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.addSubview(topVm)
        view.addSubview(searchVm)
        view.addSubview(tableView)
        
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: self.tableView.frame.height*0.5)
    }
}


extension MercPermanceListVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        emptyView.isHidden = dataSourceArray.count > 0 ? true : false
        return dataSourceArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PerformanceMercTableViewCell") as! PerformanceMercTableViewCell
        
        let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
        cell.updateUI(dict: dict)
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kFitWidth(216)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
        
        let vc = MercPermanceDetailVC()
        vc.name = dict["name"]as? String ?? ""
        vc.phone = dict["phone"]as? String ?? ""
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension MercPermanceListVC{
    func sendDataListRequest() {
        MCToast.mc_loading()
        let urlString = "\(URL_posMerchantTradeTotal)?startTime=\(startTime)&endTime=\(endTime)&phone=\(phone)&pageNum=\(pageNum)&pageSize=\(pageSize)"
        
        WHNetworkUtil.shareManager().GET(urlString: urlString) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            self.tableView.mj_footer!.endRefreshing()
            self.tableView.mj_header!.endRefreshing()
            
            if responseObject["code"]as? Int ?? 0 == 200 {
                let dataObj = responseObject["data"]as? NSDictionary ?? [:]
                let dataArr = dataObj["list"]as? NSArray ?? []
                
                if self.pageNum == 1{
                    self.dataSourceArray.removeAllObjects()
                }
                self.dataSourceArray.addObjects(from: dataArr as! [Any])
                // 提示没有更多数据
                if dataArr.count < self.pageSize {
                    self.tableView.mj_footer!.endRefreshingWithNoMoreData()
                }
                
                self.tableView.reloadData()
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "网络异常")", viewController: self)
            }
        }
    }
}
